<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { updateProcureApi, checkStockApi } from '@/apis/order'

interface Props {
  visible: boolean,
  info: any
}

const props = defineProps<Props>()
const emit = defineEmits(['confirm', 'update:visible'])

const formData = ref({
  ch_order_num: '',
  ch_order_info: '',
  open_inventory: 2
})

watch(() => props.info, (val) => {
  formData.value = {
    ch_order_num: val.ch_order_num,
    ch_order_info: val.ch_order_info,
    open_inventory: val.ch_order_info || 2
  }
})

/** 关闭弹窗 */
const handleClose = () => {
  formData.value = {
    ch_order_num: '',
    ch_order_info: '',
    open_inventory: 2
  }
  emit('update:visible', false)
  console.log('关闭')
}

const handleConfirm = async () => {

  /** 校验库存 */
  if (formData.value.open_inventory === 1) {
    const res = await checkStockApi({
      shop_sku: props.info.shop_sku
    })
    if (!res.shop_inventory && res.shop_inventory <= 0) return ElMessage.error('库存不足')
  }

  const params = {
    ...props.info, 
    ...formData.value, 
    status: formData.value.open_inventory === 1 ? 2 : props.info.status
  }

  const res = await updateProcureApi(params)
  ElMessage.success(res.msg)
  emit('confirm')
  handleClose()
}
</script>

<template>
  <el-dialog :model-value="visible" title="编辑采购信息" width="500" @close="handleClose">
    <!-- 对话框内容插槽 -->
    <el-form label-width="100" label-position="left">
      <el-form-item label="是否使用库存">
        <el-radio-group v-model="formData.open_inventory">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <template v-if="formData.open_inventory === 2">
      <el-form-item label="订单号">
        <el-input v-model="formData.ch_order_num" placeholder="请输入采购订单号" />
      </el-form-item>
      <el-form-item label="采购信息">
        <el-input type="textarea" v-model="formData.ch_order_info" placeholder="请输入采购颜色、尺寸等信息" />
      </el-form-item>
    </template>
    </el-form>

    <!-- 自定义底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
